package com.module.overview.ui.cardHistoryDetails.provider

import android.graphics.Typeface
import android.os.CountDownTimer
import android.util.Log
import android.view.View
import android.widget.TextView
import com.chad.library.adapter.base.provider.BaseItemProvider
import com.chad.library.adapter.base.viewholder.BaseViewHolder
import com.common.app.data.bean.CalendarDay
import com.common.app.data.bean.KeyEvents
import com.common.app.data.bean.overView.CardSettingModel
import com.common.app.data.bean.overView.HistoryDetailsModel
import com.common.app.utls.TimeUtils
import com.common.base.app.extras.enable
import com.common.base.app.extras.formatToFloat
import com.common.base.app.extras.otherwise
import com.common.base.app.extras.setText
import com.common.base.app.extras.setVisibility
import com.common.base.app.extras.showToast
import com.common.base.app.extras.yes
import com.common.base.utils.SpanUtils
import com.common.base.utils.ToastUtils
import com.common.base.utils.ToastUtils.showToast
import com.common.base.utils.ViewUtils
import com.common.base.utils.ViewUtils.getString
import com.jeremyliao.liveeventbus.LiveEventBus
import com.module.ble.data.bean.CusChartData
import com.module.ble.db.table.UserBloodOxygen
import com.module.ble.db.table.UserBodyTemperature
import com.module.ble.db.table.UserHeartRate
import com.module.ble.listener.CusConnectBleDeviceExpandListener
import com.module.ble.listener.CusSynthesisHealthExpandListener
import com.module.ble.utils.AizoSDKUtil
import com.module.ble.utils.AllCardTypeConfig
import com.module.ble.utils.CommonCusHealthType
import com.module.ble.widget.CandlestickChart
import com.module.ble.widget.StressBarChart
import com.module.ble.widget.StressBrokenLineChart
import com.module.overview.R

/**
 *
 * 作者：sosou
 *
 * 版本：1.0
 *
 * 创建日期：2025/7/10
 *
 * 描述：体征-心率卡片
 *
 * 修订历史：
 *
 */
class OvSignsHrCardOldProvider(mCalendar: CalendarDay?,
                               override val itemViewType: Int = AllCardTypeConfig.TYPE_CARD_SIGNS_HR,
                               override val layoutId: Int = R.layout.overview_signs_hr_old_crad_provider
) : BaseItemProvider<HistoryDetailsModel>() {

    var tvAverageHr: TextView? = null
    var tvMeasure: TextView? = null
    var candlestickChart: CandlestickChart? = null

    private val earlyMorningStr = getString(R.string.common_rail_unit)
    private val morningStr  = getString(R.string.common_rail_unit)
    private val afternoonStr  = getString(R.string.common_rail_unit)
    private val eveningStr  = getString(R.string.common_rail_unit)

    // 设置数据（48个30分钟间隔的数据）
    private val stressData = mutableListOf<CusChartData>()
    private var averageDataValues = mutableListOf<CusChartData>()
//
//    var isComplete = false
//    private var mMaxCountDown = 65 * 1000L
//    var mBtnCountDownTimer: CountDownTimer? = null
    var mCalendar = mCalendar

    init {
        val currentTime = System.currentTimeMillis()
        val startOfDay = currentTime - (currentTime % (24 * 60 * 60 * 1000)) // 当天0点时间戳

        for (index in 0 until 48) {
            val timeOffset = index * 30 * 60 * 1000L // 每30分钟的时间偏移
            val timestamp = startOfDay + timeOffset

            // 根据实际压力数据设置值（0-100）
            val minValue = when {
                index < 12 -> (40 + (10..30).random()).toFloat() // 0-6点
                index < 24 -> (40 + (10..40).random()).toFloat() // 6-12点
                else -> (40 + (1..20).random()).toFloat() // 12-24点
            }

            stressData.add(
                CusChartData(
                    createdTime = timestamp,
                    minValue = minValue,
                    mValue = minValue+(1..20).random(),
                    dayNum = 0
                )
            )
        }

        // 设置特殊值
        stressData[2] = stressData[2].copy(mValue = 41f, minValue = 40f)
//        stressData[3] = stressData[3].copy(mValue = 20f)
        stressData[4] = stressData[4].copy(mValue = 40f, minValue = 40f)
        stressData[5] = stressData[5].copy(mValue = 90f, minValue = 80f)
        stressData[6] = stressData[6].copy(mValue = 100f, minValue = 80f)
//        stressData[7] = stressData[7].copy(mValue = -1f)
//        stressData[8] = stressData[8].copy(mValue = -1f)
//        stressData[40] = stressData[40].copy(mValue = 77f)
        stressData[15].selectBg = true
        stressData[16].selectBg = true
        stressData[17].selectBg = true
        stressData[19].selectBg = true

        stressData.forEach {
            averageDataValues.add(
                CusChartData(
                    createdTime = it.createdTime,
                    minValue = it.minValue,
                    mValue = (it.minValue+((it.mValue-it.minValue)/2)),
                    dayNum = 0
                )
            )
        }


        averageDataValues[4] = stressData[4].copy(mValue = -1f, minValue = -1f)
        averageDataValues[5] = stressData[5].copy(mValue = -1f, minValue = -1f)
        averageDataValues[6] = stressData[6].copy(mValue = -1f, minValue = -1f)
        averageDataValues[31] = averageDataValues[31].copy(mValue = -1f, minValue = -1f)
//        averageDataValues[32] = averageDataValues[32].copy(mValue = -1f, minValue = -1f)
    }

    override fun convert(helper: BaseViewHolder, item: HistoryDetailsModel) {
        // 设置Y轴阶段
        candlestickChart?.setYAxisStages(
//            floatArrayOf(40f, 80f, 90f, 120f), // 阶段分界点
            floatArrayOf(40f, 80f, 120f), // 阶段分界点
        )
        // 在代码中设置数据
        candlestickChart?.setData(stressData)

        candlestickChart?.setAverageData(averageDataValues)


        // 设置触摸监听
        candlestickChart?.setOnBarTouchListener(object : CandlestickChart.OnBarTouchListener {
            override fun onBarTouched(
                index: Int,
                minValue: Float,
                maxValue: Float,
                timeLabel: String,
                extStr: String
            ) {
                // 处理触摸事件
//                Log.d("CandlestickChart", "触摸到柱子: 索引=$barIndex,触摸到: $timeLabel, 值: $minValue")
                helper.setText(R.id.tvAverageHr, (minValue+((maxValue-minValue)/2)).toInt().toString())
            }

            override fun onAverageLineTouched(
                index: Int,
                minValue: Float,
                maxValue: Float,
                timeLabel: String,
                extStr: String
            ) {
            }

            override fun onTouchReleased() {
                // 处理触摸释放事件
            }
        })
    }


    override fun onViewHolderCreated(viewHolder: BaseViewHolder, viewType: Int) {
        tvAverageHr = viewHolder.getView(R.id.tvAverageHr)
        tvMeasure = viewHolder.getView(R.id.tvMeasure)
        candlestickChart = viewHolder.getView(R.id.candlestickChart)
        viewHolder.setVisible(R.id.tvMeasure, (mCalendar?.dateName == getString(R.string.common_today_hint)))
        LiveEventBus.get(KeyEvents.KEY_OV_SET_HR_MEASUREMENT_LISTENER).post(this)
        super.onViewHolderCreated(viewHolder, viewType)
    }
}